package org.xiaom.butler.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.os.Environment;

public class FileHelper {

	private Context context;

	/** SD卡的路径 **/

	private String SDPATH;

	/** 当前程序包的路径 **/

	private String FILESPATH;

	public FileHelper(Context context, String path) {
		this.context = context;
		SDPATH = Environment.getExternalStorageDirectory().getPath()+"/"+path;
		FILESPATH = this.context.getFilesDir().getPath();
	}

	/**
	 * 在SD卡上创建文件
	 */
	public String createSDFile(String fileName, InputStream fin) {
		String path = SDPATH + fileName;
		//此pathFile用来创建file的父级文件夹
		File pathFile = new File(SDPATH);
		File file = new File(path);
		FileOutputStream fout = null;
		try {
			if (!pathFile.exists()) {
				pathFile.mkdirs();
				pathFile = null;
			}
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			fout = new FileOutputStream(file);
			byte[] b = new byte[1024];
			int l;
			while ((l = fin.read(b)) > 0) {
				fout.write(b, 0, l);
			}
		} catch (IOException e) {
			e.printStackTrace();
			path = "";
		} finally {
			try {
				fout.close();
			} catch (Exception e) {
			}
		}
		return path;
	}

	/**
	 * 
	 * 删除SD卡上的文件
	 * 
	 * 
	 * 
	 * @param fileName
	 */

	public boolean deleteSDFile(String fileName) {
		File file = new File(SDPATH + "//" + fileName);
		if (file == null || !file.exists() || file.isDirectory())
			return false;
		return file.delete();
	}

	/**
	 * 
	 * 读取SD卡中文本文件
	 * 
	 * 
	 * 
	 * @param fileName
	 * 
	 * @return
	 */

	public String readSDFile(String fileName) {

		StringBuffer sb = new StringBuffer();

		File file = new File(SDPATH + "//" + fileName);

		try {

			FileInputStream fis = new FileInputStream(file);

			int c;

			while ((c = fis.read()) != -1) {

				sb.append((char) c);

			}

			fis.close();

		} catch (FileNotFoundException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return sb.toString();

	}

	public String getFILESPATH() {

		return FILESPATH;

	}

	public String getSDPATH() {

		return SDPATH;

	}
}
